<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use app\common\model\enneagram\Questions;
use app\common\model\enneagram\Results;
use app\common\model\enneagram\Types;
use stdClass;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;
use Throwable;

class Enneagram extends Frontend
{
    // 无需登录的方法
    // protected array $noNeedLogin = ['*'];

    // 无需鉴权的方法
    protected array $noNeedPermission = ['*'];


    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 九型人格测试首页
     */
    public function index()
    {
        $questions = Questions::field('title,option_a_text,option_a_type,option_a_weight,option_b_text,option_b_type,option_b_weight,weigh')->select();
        $total_questions = Questions::getTotalQuestions();
        $time_limit_minutes = Questions::getTimeLimitMinute();
        $this->success('九型人格测试系统', compact('questions', 'total_questions', 'time_limit_minutes'));
    }


    /**
     * 用户开始测试,分登陆和未登陆用户
     */
    public function start()
    {
        // // 如果是未登陆用户
        // if (!$this->auth->isLogin()) {
        //     // 创建新测试
        //     $this->success('测试开始', Results::createTest());
        // }

        $userId = $this->auth?->id ?: 0;
        // // 检查是否有未完成的测试
        // if ($userId) {
        //     $unfinishedTest = Results::where(['user_id' => $userId, 'isFinish' => 0])->findOrEmpty();
        //     if (!$unfinishedTest->isEmpty()) {
        //         // 检查测试是否已超时
        //         $timeElapsed = (time() - $unfinishedTest->create_time) / 60; // 转换为分钟
        //         $time_limit_minutes = Questions::getTimeLimitMinute();
        //         if ($timeElapsed > $time_limit_minutes) {
        //             $finishResult = $this->transCalcResult($unfinishedTest);
        //             $this->success('测试已超时自动完成', $finishResult->toArray());
        //         }
        //         $this->success('测试开始', $unfinishedTest->toArray());
        //     }
        // }

        $this->success('测试开始', Results::createTest($userId));
    }


    /**
     * 提交答案
     */
    public function submit()
    {
        // 验证参数
        $validate = Validate::rule([
            'id' => 'require|number',
            'question_id' => 'require|number',
            'selected_option' => 'require|in:A,B,a,b'
        ]);

        $params = $this->request->post();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $resultId = $params['id'];
        $questionId = $params['question_id'];
        $selected_option = strtolower($params['selected_option']);

        // 检查测试是否存在且未完成
        $test = Results::where(['id' => $resultId])->findOrEmpty();
        if ($test->isEmpty()) {
            return $this->error('测试不存在！');
        }
        if ($test->isFinish == 1) {
            return $this->error('测试已完成！');
        }

        // 检查测试是否已超时
        $timeElapsed = (time() - $test->create_time) / 60; // 转换为分钟
        // 检查是否超时

        $time_limit_minutes = Questions::getTimeLimitMinute();
        if ($timeElapsed > $time_limit_minutes) {
            $finishResult = $this->transCalcResult($test);
            $this->success('测试已超时，已自动提交报告', $finishResult);
        }

        $selected_options = $test->selected_options;
        if (!is_object($selected_options)) {
            $selected_options = new stdclass;
        }
        $selected_options->$questionId = $selected_option;
        // 检查是否已完成所有题目，暂时不考虑
        // if (count((array)$selected_options) >= self::TOTAL_QUESTIONS) {
        //     // 完成测试，并生成报告
        //     $finishResult = $test->calculateThresholdResult($test);
        //     return $this->success('恭喜您完成了所有题目！', $finishResult);
        // }
        $test->selected_options = $selected_options;
        $test->save();
        $this->success('答案已提交', $test);
    }

    /**
     * 计算得分，包括所有自动完成，非用户主动提交的计算分析
     */
    public function calculate()
    {

        $userId = $this->auth?->id;
        // 验证参数
        $validate = Validate::rule([
            'id' => 'require|number'
        ]);
        $post = $this->request->post();
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $testId = $post['id'];
        // 检查测试是否存在且已完成
        $test = Results::where(array_merge(['id' => $testId], ($userId ? ['user_id' => $userId] : [])))->findOrEmpty();
        if ($test->isEmpty()) {
            $this->error('测试不存在！');
        }

        $this->transCalcResult($test);
        $this->success('计算完成');
    }

    /**
     * 获取测试报告
     */
    public function report()
    {
        // // 检查用户是否登录
        // if (!$this->auth->isLogin()) {
        //     return $this->error('请先登录');
        // }

        $userId = $this->auth?->id;

        // 验证参数
        $validate = Validate::rule([
            'id' => 'require|number'
        ]);

        $params = $this->request->get();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $testId = $params['id'];

        // 检查测试是否存在且已完成
        $test = Results::where(array_merge(['id' => $testId], ($userId ? ['user_id' => $userId] : [])))->findOrEmpty();
        if ($test->isEmpty()) {
            $this->error('测试不存在！');
        }
        if ($test->isFinish == 0) {
            $this->error('测试未完成！');
        }
        //如果为必须支付就判断是否支付了
        $pay_is_required = get_sys_config('pay_is_required');
        if ($pay_is_required == '1' && $test->pay_status != Results::PAY_STATUS_PAID) {
            $this->success('请先支付解锁！', ['id' => $test->id, 'pay_is_required' => $pay_is_required]);
        }


        // 获取测试结果
        // $this->transCalcResult($test);
        $report = $test->report_data;
        $enneagramTypes = Types::field('type,name')->order('type', 'asc')->select()?->toArray();
        $this->success('测试报告', compact('report', 'enneagramTypes'));
    }
    /**
     * 海报数据
     */
    public function poster()
    {
        // // 检查用户是否登录
        // if (!$this->auth->isLogin()) {
        //     return $this->error('请先登录');
        // }

        $userId = $this->auth?->id;

        // 验证参数
        $validate = Validate::rule([
            'id' => 'require|number'
        ]);

        $params = $this->request->get();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $testId = $params['id'];

        // 检查测试是否存在且已完成
        $poster = Results::field('id,main_type,order_id,pay_status,create_time,isFinish,user_id')->where(array_merge(['id' => $testId], ($userId ? ['user_id' => $userId] : [])))->findOrEmpty();
        if ($poster->isEmpty()) {
            $this->error('测试不存在！');
        }
        if ($poster->isFinish == 0) {
            $this->error('测试未完成！');
        }
        // 获取测试结果
        $enneagramTypes = Types::field('type,name,description')->order('type', 'asc')->select()?->toArray();
        $enneagramTypes = collect($enneagramTypes)->map(function ($item) {
            $item['description'] = explode(PHP_EOL, $item['description']);
            if (is_array($item['description']) && !empty($item['description'])) {
                $randomKey = array_rand($item['description']);
                $item['description'] = $item['description'][$randomKey];
            }
            return $item;
        });
        $this->success('海报数据', compact('poster', 'enneagramTypes'));
    }

    private function transCalcResult(Results $result)
    {
        Db::startTrans();
        try {
            $finishResult = $result->calculateThresholdResult($result);
            Db::commit();
            return $finishResult;
        } catch (Throwable $e) {
            Db::rollback();
            $this->success('生成测试结果出错！: ' . $e->getMessage());
        }
    }
    public function toPay()
    {
        // 验证参数
        $validate = Validate::rule([
            'id' => 'require|number',
        ]);

        $params = $this->request->get();
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $resultId = $params['id'];

        // 检查测试是否存在且未完成
        $userId = $this->auth?->id;
        $test = Results::where(array_merge(['id' => $resultId], ($userId ? ['user_id' => $userId] : [])))->findOrEmpty();
        if ($test->isEmpty()) {
            $this->error('报告不存在！');
        }
        $price = get_sys_config('enneagram_test_price');
        if (empty($price)) {
            $this->error('测试价格未设置！');
        }
        // 将价格转为字符串并保留1位小数进行比较
        $formattedPrice = number_format(floatval($price), 2, '.', '');
        // 价格必须大于0且是有效数字
        if (!is_numeric($formattedPrice) || bccomp($formattedPrice, '0.00', 2) <= 0) {
            $this->error('测试价格错误！必需是大于0的有效数字！');
        }

        $this->success('支付数据', ['price' => $formattedPrice, 'paid' =>  $test->pay_status == Results::PAY_STATUS_PAID ? 'Y' : 'N']);
    }
}
